package com.yueyang.sojourn.server.config;

import com.yueyang.sojourn.server.common.LoginNeedless;
import com.yueyang.sojourn.server.common.baymax.web.result.JAssert;
import com.yueyang.sojourn.server.common.consts.Constants;
import com.yueyang.uc.UserType;
import com.yueyang.uc.model.LoginTokenV1;
import com.yueyang.uc.model.UcLoginUserV1;
import com.yueyang.uc.spi.LoginUserSpi;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Stephen.Shi
 * @version v1
 * @summary 管理员用户登录校验
 * @Copyright (c) 2019, yueyang Group All Rights Reserved.
 * @since 2020/2/1
 */
public class AdminLoginInteceptor implements HandlerInterceptor {
    @Autowired
    private LoginUserSpi loginUserSpi;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(Constants.LOGIN_TOKEN);

        if(handler instanceof HandlerMethod) {
            HandlerMethod h = (HandlerMethod)handler;
            LoginNeedless loginNeedless = h.getMethodAnnotation(LoginNeedless.class);
            // 需要登录
            if (loginNeedless == null) {
                JAssert.authorized(StringUtils.isNotBlank(token), "未登录");
                loginUserSpi.authorized(token);
                LoginTokenV1 loginTokenV1 = loginUserSpi.authorized(token);
                JAssert.authorized(loginTokenV1 != null, "获取登录token失败");
                UcLoginUserV1 loginUserV1 = loginUserSpi.userInfo(loginTokenV1.getToken());
                JAssert.authorized(loginUserV1 != null, "登录已失效");
                JAssert.authorized(loginUserV1.getType().intValue() == UserType.后台用户.getValue(), "登陆人不是后台用户");
                AppUtil.setUseToThread(loginUserV1);
            }
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求结束后，移除threadLocal中的登陆人信息
        AppUtil.removeUserFromThread();
    }
}
